package br.com.tiespec.web.ManagedBean;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PreDestroy;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

import org.primefaces.context.RequestContext;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import br.com.tiespec.ejb.EjbInterface.CenarioBaseInterface;
import br.com.tiespec.model.Enum.TipoSortOrder;
import br.com.tiespec.model.Modelo.CenarioBase;
import br.com.tiespec.model.Modelo.FluxoBase;
import br.com.tiespec.model.Util.RNException;
import br.com.tiespec.web.Util.InitUtil;
import br.com.tiespec.web.Util.MsgUtil;
import br.com.tiespec.web.Util.WebUtil;

@Named("cenarioBaseBean")
@SessionScoped
public class CenarioBaseBean implements Serializable {

	private static final long serialVersionUID = 1602853470341561435L;

	@EJB private CenarioBaseInterface ejb;
	
	private CenarioBase cenarioBaseInstance;
	private LazyDataModel<CenarioBase> cenarioBaseList;
	private CenarioBase[] cenariosSelecionados;
	private String msgExclusao;
	
	private Long idClientePortal;
	private String varNome;
	private String varFluxo;
	
	public String cenarioBase(){
		init();
		return "/views/cenarioBase/show.xhtml";
	}
	
	private void init(){
		cenarioBaseInstance = new CenarioBase();
		cenarioBaseList = InitUtil.inicializaCenarioBaseList();
		varNome = null;
		varFluxo = null;
		cenariosSelecionados = new CenarioBase[0];
	}
	
	public String goDesistir(){
		return "/views/cenarioBase/show.xhtml";
	}
	
	public String goCreate(){
		cenarioBaseInstance = new CenarioBase();
		cenarioBaseInstance.setFluxosBase(new ArrayList<FluxoBase>());
		cenarioBaseInstance.setResponsavelCadastro(WebUtil.getUsuarioLogado());
		cenarioBaseInstance.setCliente(WebUtil.getUsuarioLogado().getCliente());
		FluxoBase fTemp = new FluxoBase();
		fTemp.setAcao("O usuário realiza alguma ação");
		fTemp.setCodFluxo("1");
		cenarioBaseInstance.getFluxosBase().add(fTemp);
		return "/views/cenarioBase/create.xhtml"; 
	}
	
	public void save(){
		try {
			ejb.salvarCenario(cenarioBaseInstance);
			MsgUtil.msgSucesso("inc", cenarioBaseInstance.getNome());
		} catch (RNException e) {
			MsgUtil.msgErro("inc", cenarioBaseInstance.getNome());
			e.printStackTrace();
		}
	}
	
	public String goEdit(Long id){
		cenarioBaseInstance = ejb.selecionarCenarioBaseComFluxosEResponsavel(id);
		return "/views/cenarioBase/edit.xhtml";
	}
	
	public String update(){
		try {
			ejb.atualizarCenario(cenarioBaseInstance);
			MsgUtil.msgSucesso("atu", cenarioBaseInstance.getNome());
			return "/views/cenarioBase/show.xhtml";
		} catch (RNException e) {
			MsgUtil.msgErro("atu", cenarioBaseInstance.getNome());
			e.printStackTrace();
			return null;
		}
	}
	
	public void goDelete(){
 		RequestContext requestContext = RequestContext.getCurrentInstance();
		Integer length = cenariosSelecionados.length;
		if (length == 0){
			requestContext.execute("dialogoSelecione.show()");
			return;
		}
		String tmp = "";
		if (length == 1){
			msgExclusao = MsgUtil.getMensagem("DialogoExcluir_MensagemUnico", cenariosSelecionados[0].getNome());
		} else {
			tmp = "'";
			Integer count = 0;
			for(CenarioBase c:cenariosSelecionados){
				tmp += c.getNome();
				count++;
				if (count==length-1)
					tmp += "' e '";
				else if (count==length)
					tmp += "'";
				else
					tmp += "', '";
			}
		}
		msgExclusao = MsgUtil.getMensagem("DialogoExcluir_MensagemMultiplo", tmp);
		requestContext.execute("dialogoExcluir.show()");
	}
	
	public void delete(){
		for (CenarioBase c:cenariosSelecionados){
			try {
				ejb.excluirCenario(c.getId());
				MsgUtil.msgSucesso("exc", c.getNome());
			} catch (RNException e) {
				MsgUtil.msgErro("exc", c.getNome());
				e.printStackTrace();
			}
		}
		filtrarCenarioBase();
	}
	
	public void goVisualizar(Long id){
		cenarioBaseInstance = ejb.selecionarCenarioBaseComFluxos(id);
	}
	
	public void adicionarFluxo(String fluxo){
		FluxoBase f = new FluxoBase();
		f.setCodFluxo(trataProxFluxo(fluxo));
		cenarioBaseInstance.getFluxosBase().add(f);
	}
	
	private String trataProxFluxo(String s){
		String[] vtr = s.split("[/.]");
		Integer in = Integer.parseInt(vtr[vtr.length-1]);
		in++;
		s = "";
		for (int i = 0; i<vtr.length-1; i++)
			s += vtr[i] + ".";
		s += in;
		return s;
	}
	
	public void removerFluxo(String fluxo){
		if (cenarioBaseInstance.getFluxosBase().size() == 1)
			return;
		FluxoBase remover = pegarFluxo(fluxo);
		if (remover!=null)
			cenarioBaseInstance.getFluxosBase().remove(remover);
	}
	
	private FluxoBase pegarFluxo(String codFluxo){
		for (FluxoBase f:cenarioBaseInstance.getFluxosBase()){
			if (f.getCodFluxo().equals(codFluxo)){
				return f;
			}
		}
		return null;
	}
	
	private void mudarTabulacao(String fluxo, String novoCod){
		for (FluxoBase f:cenarioBaseInstance.getFluxosBase()){
			if (f.getCodFluxo().equals(fluxo)){
				f.setCodFluxo(novoCod);
				break;
			}
		}
	}
	
	public void aumentarTabulacao(String fluxo){
		mudarTabulacao(fluxo, fluxo + ".1");
		//TODO refatorar o resto
	}
	
	public void diminuirTabulacao(String fluxo){
		if (!fluxo.contains("."))
			return;
		String s = fluxo.substring(0, fluxo.lastIndexOf("."));
		mudarTabulacao(fluxo, s);
	}
	
	public void filtrarTodos(){
		varNome = "";
		varFluxo = "";
		filtrarCenarioBase();
	}
	
	@SuppressWarnings("serial")
	public void filtrarCenarioBase(){
		cenarioBaseList = new LazyDataModel<CenarioBase>() {
			@Override
			public List<CenarioBase> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters) {
				WebUtil.setDataTableRows(pageSize);
				return ejb.listarCenarioBase(first, pageSize, sortField, 
					TipoSortOrder.convertePrimeFaces(sortOrder.toString()), idClientePortal, varNome, varFluxo);
			}
			@Override  
	        public CenarioBase getRowData(String rowKey) {  
	        	try {
		            return ejb.selecionarCenarioBase(Long.parseLong(rowKey));
	        	} catch (NumberFormatException e){
	        		return new CenarioBase();
	        	}
	        }  
	        @Override  
	        public String getRowKey(CenarioBase objeto) {  
	        	if (objeto!=null)
	        		return ""+objeto.getId();
	        	return "";
	        }  
		};
		cenarioBaseList.setRowCount(ejb.countCenarioBase(idClientePortal, varNome, varFluxo));
		cenarioBaseList.setPageSize(5);
	}
	
	public String goHome(){
		this.destroy();
		return "goHome";
	}
	
	@PreDestroy
	public void destroy(){
		cenarioBaseInstance = null;
		cenarioBaseList = null;
		cenariosSelecionados = null;
		msgExclusao = null;
		idClientePortal = null;
		varNome = null;
		varFluxo = null;
	}

	public CenarioBase getCenarioBaseInstance() {
		return cenarioBaseInstance;
	}

	public void setCenarioBaseInstance(CenarioBase cenarioBaseInstance) {
		this.cenarioBaseInstance = cenarioBaseInstance;
	}

	public LazyDataModel<CenarioBase> getCenarioBaseList() {
		return cenarioBaseList;
	}

	public void setCenarioBaseList(LazyDataModel<CenarioBase> cenarioBaseList) {
		this.cenarioBaseList = cenarioBaseList;
	}

	public String getVarNome() {
		return varNome;
	}

	public void setVarNome(String varNome) {
		this.varNome = varNome;
	}

	public String getVarFluxo() {
		return varFluxo;
	}

	public void setVarFluxo(String varFluxo) {
		this.varFluxo = varFluxo;
	}
	
	public CenarioBase[] getCenariosSelecionados() {
		return cenariosSelecionados;
	}
	
	public void setCenariosSelecionados(CenarioBase[] cenariosSelecionados) {
		this.cenariosSelecionados = cenariosSelecionados;
	}
	
	public String getMsgExclusao() {
		return msgExclusao;
	}
	
	public void setMsgExclusao(String msgExclusao) {
		this.msgExclusao = msgExclusao;
	}
}